<template>
    <div class="add">
        <div class="title">
            <h1>{{ patientParam.id || $route.query.id ? '修改' : '添加' }}就诊人</h1>
        </div>
        <div class="content">
            <div class="subTitle">
                就诊人信息
            </div>
            <div class="patientInfo">
                <el-form class="form" ref="patientRef" :rules="patientRules" label-width="100px" :inline="true"
                    :model="patientParam">
                    <el-form-item label="姓名：" prop="name">
                        <el-input v-model="patientParam.name" placeholder="请输入真实姓名全称"></el-input>
                    </el-form-item>
                    <el-form-item label="证件类型：" prop="certificatesType">
                        <el-select v-model="patientParam.certificatesType" style="width:300px" placeholder="请选择证件类型"
                            clearable>
                            <el-option :value="item.value" :label="item.name" v-for="(item, index) in cardType"
                                :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="证件号码：" prop="certificatesNo">
                        <el-input v-model="patientParam.certificatesNo" placeholder="请输入证件号码"></el-input>
                    </el-form-item>
                    <el-form-item label="性别：" prop="sex">
                        <el-radio-group v-model="patientParam.sex">
                            <el-radio :value="1">男</el-radio>
                            <el-radio :value="0">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="出生日期：" prop="birthdate">
                        <el-date-picker v-model="patientParam.birthdate" type="date" placeholder="请选择出生日期" />
                    </el-form-item>
                    <el-form-item label="手机号码：" prop="phone">
                        <el-input v-model="patientParam.phone" placeholder="请输入手机号码"></el-input>
                    </el-form-item>
                </el-form>

            </div>
            <div class="subTitle">
                建档信息（完善后部分医院首次就诊不排队建档）
            </div>
            <div class="patientInfo">
                <el-form :rules="deatilRules" class="form" :model="patientParam" ref="detailRef" label-width="100px"
                    :inline="true">
                    <el-form-item label="婚姻状况：" prop="isMarry">
                        <el-radio-group v-model="patientParam.isMarry">
                            <el-radio :value="0">未婚</el-radio>
                            <el-radio :value="1">已婚</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="自费/医保：" prop="isInsure">
                        <el-radio-group v-model="patientParam.isInsure">
                            <el-radio :value="0">自费</el-radio>
                            <el-radio :value="1">医保</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="当前住址：" prop="addressSelected">
                        <el-cascader v-model="patientParam.addressSelected" :props="prop" placeholder="请选择当前住址" />
                    </el-form-item>
                    <el-form-item label="详细地址：" prop="address">
                        <el-input v-model="patientParam.address" placeholder="应公安机关要求，请填写现真实地址"></el-input>
                    </el-form-item>
                </el-form>

            </div>
            <div class="subTitle">
                联系人信息（选填）
            </div>
            <div class="patientInfo">
                <el-form class="form" label-width="100px" :inline="true" :model="patientParam">
                    <el-form-item label="姓名：">
                        <el-input v-model="patientParam.contactsName" placeholder="请输入联系人姓名全称"></el-input>
                    </el-form-item>
                    <el-form-item label="证件类型：">
                        <el-select v-model="patientParam.contactsCertificatesType" style="width:300px"
                            placeholder="请选择联系人证件类型" clearable>
                            <el-option :value="item.value" :label="item.name" v-for="(item, index) in cardType"
                                :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="证件号码：">
                        <el-input v-model="patientParam.contactsCertificatesNo" placeholder="请输入联系人证件号码"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号码：">
                        <el-input v-model="patientParam.contactsPhone" placeholder="请输入联系人手机号码"></el-input>
                    </el-form-item>
                </el-form>

            </div>
            <div class="btn">
                <el-button type="primary" size="large" @click="submit">保存</el-button>
                <el-button type="info" size="large" @click="reset">重置</el-button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { useUserInfo } from '../../certification/composables/useUserInfo';
import { CascaderProps, ElMessage } from 'element-plus';
import { addORUpdatePatientAPI, getCityAPI } from '@/api/user';
import { patientParams } from '@/api/user/type';
import { useRoute, useRouter } from 'vue-router';
import { usePatient } from '../composables/usePatient';

let { cardType, getUserInfo } = useUserInfo()

onMounted(() => {
    getUserInfo()
    judge()
})
let { patientData, getPatient } = usePatient()
//自定义校验规则姓名方法
const validatorName = (rule: any, value: any, callBack: any) => {
    //rule:即为当前校验字段的校验规则对象
    const reg = /^[\u00B7\u3007\u3400-\u4DBF\u4E00-\u9FFF\uE000-\uF8FF\uD840-\uD8C0\uDC00-\uDFFF\uF900-\uFAFF]+$/;
    if (reg.test(value)) {
        callBack();
    } else {
        callBack(new Error("请输入正确的用户姓名"));
    }
};
//证件号码的校验方法
const validatorNo = (rule: any, value: any, callBack: any) => {
    let sfz = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/;
    let hkb = /^\d{9}$/;
    if (sfz.test(value) || hkb.test(value)) {
        callBack();
    } else {
        callBack(new Error("请输入正确的身份证或者户口本的号码"));
    }
};
//自定义校验规则:手机号码自定义校验规则
const validatorPhone = (rule: any, value: any, callBack: any) => {
    //rule:即为表单校验规则对象
    //value:即为当前文本的内容
    //callBack:回调函数
    const reg = /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/;
    if (reg.test(value)) {
        callBack();
    } else {
        callBack(new Error("请输入正确的手机号码"));
    }
};
const patientRules = {
    name: [{ required: true, validator: validatorName }],
    certificatesType: {
        required: true,
        message: '请选择证件类型',
        trigger: 'change',
    },
    certificatesNo: {
        required: true,
        validator: validatorNo,
    },
    sex: {
        required: true,
        message: '请选择性别',
        trigger: 'change',
    },
    birthdate: {
        required: true,
        message: '请选择出生日期',
        trigger: 'change',
    },
    phone: [{ required: true, validator: validatorPhone }]
}
let patientRef = ref()
let detailRef = ref()
const deatilRules = {
    isMarry: {
        required: true,
        message: '请选择婚姻状况',
        trigger: 'change',
    },
    isInsure: { required: true, message: '请选择自费/医保', trigger: 'change' },
    addressSelected: { required: true, message: '请选择当前住址', trigger: 'change' },
    address: { required: true, message: '请输入详细地址', trigger: 'blur' }
}

const prop: CascaderProps = {
    lazy: true,
    async lazyLoad(node, resolve) {
        let res: any = await getCityAPI(node.data?.id as string || '86')
        let showData = res.data.map((item: any) => {
            return {
                id: item.id,
                label: item.name,
                value: item.value,
                leaf: !item.hasChildren
            }
        })
        resolve(showData)
    },
}

const patientParam = reactive<patientParams>({
    id: "",
    name: "",
    certificatesType: "",
    certificatesNo: "",
    sex: 1,
    birthdate: "",
    phone: "",
    isMarry: 0,
    isInsure: 0,
    addressSelected: [],
    address: "",
    contactsName: "",
    contactsCertificatesType: "",
    contactsCertificatesNo: "",
    contactsPhone: "",
})
let $router = useRouter()
let $route = useRoute()
const submit = async () => {
    await patientRef.value.validate()
    await detailRef.value.validate()
    let res: any = await addORUpdatePatientAPI(patientParam)
    if (res.code == 200) {
        ElMessage({
            type: 'success',
            message: patientParam.id ? '更新成功' : '添加成功'
        })
        if ($route.query.type) {
            $router.back()
        } else {
            $router.push('/user/patient')
        }
    }
}
const reset = () => {
    Object.assign(patientParam, {
        id: '',
        name: "",
        certificatesType: "",
        certificatesNo: "",
        sex: 1,
        birthdate: "",
        phone: "",
        isMarry: 0,
        isInsure: 0,
        addressSelected: [],
        address: "",
        contactsName: "",
        contactsCertificatesType: "",
        contactsCertificatesNo: "",
        contactsPhone: "",
    })
    detailRef.value.resetFields()
    patientRef.value.resetFields()
}
const judge = () => {
    if ($route.query.id) {
        getPatient($route.query.id as string).then(item => {
            Object.assign(patientParam, patientData.value);
            if (patientData.value?.provinceCode && patientData.value?.cityCode && patientData.value?.districtCode) {
                patientParam.addressSelected.push(patientData.value?.provinceCode);
                patientParam.addressSelected.push(patientData.value?.cityCode);
                patientParam.addressSelected.push(patientData.value?.districtCode);
            }
        })
    }
}
</script>

<style scoped lang="scss">
.add {

    .title {
        h1 {
            font-weight: bold;
        }
    }

    .content {

        .subTitle {
            letter-spacing: 1px;
            color: #999;
            margin-top: 80px;
            display: flex;
            align-items: center;

            &::before {
                display: inline-block;
                content: '';
                height: 14px;
                width: 4px;
                background: #4990f1;
                margin-right: 6px;
                border-radius: 2px;
            }
        }

        .patientInfo {
            margin-top: 50px;

            .form {
                width: 450px;
                margin: 0 auto;

                ::v-deep .el-input {
                    --el-input-width: 300px;
                }

                ::v-deep .el-form-item__label {
                    color: #999;
                }

                ::v-deep .el-form-item {
                    margin-bottom: 23px;
                }

                ::v-deep .el-date-editor {
                    --el-date-editor-width: 300px;
                }
            }
        }

        .btn {
            display: flex;
            justify-content: center;
            margin-top: 50px;
            padding-bottom: 20px;
        }
    }
}
</style>